// 加载购物车商品
function loadCartItems() {
    const cartItems = JSON.parse(localStorage.getItem('cart')) || [];
    const cartItemsContainer = document.getElementById('cartItems');
    const totalQuantityElement = document.getElementById('totalQuantity');
    const totalPriceElement = document.getElementById('totalPrice');
    
    cartItemsContainer.innerHTML = '';
    
    if (cartItems.length === 0) {
        cartItemsContainer.innerHTML = '<p class="empty-cart">购物车是空的，快去选购商品吧！</p>';
        totalQuantityElement.textContent = '0';
        totalPriceElement.textContent = '¥0.00';
        return;
    }
    
    let totalQuantity = 0;
    let totalPrice = 0;
    
    cartItems.forEach(item => {
        const cartItemElement = document.createElement('div');
        cartItemElement.className = 'cart-item';
        cartItemElement.innerHTML = `
            <div class="item-image">
                <img src="${item.image}" alt="${item.name}">
            </div>
            <div class="item-info">
                <h3 class="item-name">${item.name}</h3>
                <div class="item-price">¥${item.price.toFixed(2)}</div>
            </div>
            <div class="item-quantity">
                <button class="quantity-btn minus" data-id="${item.id}">-</button>
                <span class="quantity">${item.quantity}</span>
                <button class="quantity-btn plus" data-id="${item.id}">+</button>
            </div>
            <div class="item-subtotal">¥${(item.price * item.quantity).toFixed(2)}</div>
            <button class="remove-btn" data-id="${item.id}">删除</button>
        `;
        cartItemsContainer.appendChild(cartItemElement);
        
        totalQuantity += item.quantity;
        totalPrice += item.price * item.quantity;
    });
    
    totalQuantityElement.textContent = totalQuantity;
    totalPriceElement.textContent = `¥${totalPrice.toFixed(2)}`;
    
    // 添加事件监听器
    document.querySelectorAll('.quantity-btn.minus').forEach(btn => {
        btn.addEventListener('click', decreaseQuantity);
    });
    
    document.querySelectorAll('.quantity-btn.plus').forEach(btn => {
        btn.addEventListener('click', increaseQuantity);
    });
    
    document.querySelectorAll('.remove-btn').forEach(btn => {
        btn.addEventListener('click', removeItem);
    });
}

// 减少商品数量
function decreaseQuantity(event) {
    const productId = parseInt(event.target.getAttribute('data-id'));
    updateCartItemQuantity(productId, -1);
}

// 增加商品数量
function increaseQuantity(event) {
    const productId = parseInt(event.target.getAttribute('data-id'));
    updateCartItemQuantity(productId, 1);
}

// 更新购物车商品数量
function updateCartItemQuantity(productId, change) {
    let cart = JSON.parse(localStorage.getItem('cart')) || [];
    const itemIndex = cart.findIndex(item => item.id === productId);
    
    if (itemIndex !== -1) {
        cart[itemIndex].quantity += change;
        
        if (cart[itemIndex].quantity <= 0) {
            cart.splice(itemIndex, 1);
        }
        
        localStorage.setItem('cart', JSON.stringify(cart));
        loadCartItems();
        updateCartCount();
    }
}

// 删除商品
function removeItem(event) {
    const productId = parseInt(event.target.getAttribute('data-id'));
    let cart = JSON.parse(localStorage.getItem('cart')) || [];
    cart = cart.filter(item => item.id !== productId);
    localStorage.setItem('cart', JSON.stringify(cart));
    loadCartItems();
    updateCartCount();
}

// 设置结算按钮事件
function setupCheckoutButton() {
    const checkoutBtn = document.getElementById('checkoutBtn');
    if (checkoutBtn) {
        checkoutBtn.addEventListener('click', function() {
            const cart = JSON.parse(localStorage.getItem('cart')) || [];
            if (cart.length === 0) {
                alert('购物车中没有商品');
                return;
            }
            
            if (!checkLogin()) {
                alert('请先登录');
                window.location.href = 'login.html';
                return;
            }
            
            window.location.href = 'checkout.html';
        });
    }
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    loadCartItems();
    setupCheckoutButton();
});